package com.qijian.production.controller;

import java.util.List;
import java.util.Set;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.qijian.common.core.domain.entity.SysUser;
import com.qijian.common.utils.DateUtils;
import com.qijian.common.utils.ObjectUtils;
import com.qijian.common.utils.StringUtils;
import com.qijian.production.domain.ScWorkOrder;
import com.qijian.production.domain.ScWorkOrderDetail;
import com.qijian.production.domain.query.ScWorkOrderDetailQuery;
import com.qijian.production.domain.query.ScWorkOrderQuery;
import com.qijian.production.domain.vo.ScWorkOrderDetailVo;
import com.qijian.production.domain.vo.ScWorkOrderVo;
import com.qijian.production.domain.vo.WorkOrderExcelVo;
import com.qijian.production.service.IScWorkOrderService;
import com.qijian.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import com.qijian.common.utils.mybatis.WhereEntityTool;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import lombok.SneakyThrows;
import org.apache.http.util.Asserts;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.qijian.common.annotation.Log;
import com.qijian.common.annotation.PlugAnn;
import com.qijian.common.annotation.PlugParam;
import com.qijian.common.core.controller.BaseController;
import com.qijian.common.core.domain.AjaxResult;
import com.qijian.common.core.domain.entity.FlowableApproval;
import com.qijian.common.core.domain.entity.FlowableBack;
import com.qijian.common.enums.ApprovalDescriptionEnum;
import com.qijian.common.enums.BusinessType;
import com.qijian.common.exception.ServiceException;
import com.qijian.common.utils.SecurityUtils;

import com.qijian.common.utils.poi.ExcelUtil;
import com.qijian.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
/**
 * 生产计划单Controller
 *
 * @author zhangcheng
 * @date 2025-03-25
 */
@Api(tags = "生产计划单")
@RestController
@RequiredArgsConstructor
@RequestMapping("/business/workOrder")
public class ScWorkOrderController extends BaseController {

    private final IScWorkOrderService scWorkOrderService;
    private final ISysUserService userService;

    /**
     * 查询生产计划单列表
     */
//    @PreAuthorize("@ss.hasPermi('business:workOrder:list')")
    @GetMapping("/list")
    public TableDataInfo list(ScWorkOrderQuery query, Page<ScWorkOrder> page) {
        Page<ScWorkOrderVo> workOrderVoPage;
        if (query.getSearchType().equals("1")) {
            workOrderVoPage = scWorkOrderService.pageVo(page, WhereEntityTool.invoke(query));
        }else {
            workOrderVoPage = scWorkOrderService.pageDetailVo(page, WhereEntityTool.invoke(query));
        }
        return getDataTable(workOrderVoPage);
    }

    /**
     * 查询生产计划单详情列表
     * @param query
     * @return
     */
    @GetMapping("/listDetail")
    public AjaxResult listDetail(ScWorkOrderDetailQuery query) {
        List<ScWorkOrderDetailVo> list = scWorkOrderService.listDetail(WhereEntityTool.invoke(query));
        return AjaxResult.data(list);
    }

    /**
     * 分页查询生产计划单详情列表
     * @param query
     * @param page
     * @return
     */
    @GetMapping("/pageDetail")
    public TableDataInfo pageDetail(ScWorkOrderDetailQuery query, Page<ScWorkOrderDetail> page) {
        return getDataTable(scWorkOrderService.pageDetail(page, WhereEntityTool.invoke(query)));
    }

    /**
     * 查询生产计划单详情列表
     * @param query
     * @return
     */
    @GetMapping("/listDetailForProduction")
    public AjaxResult listDetailForProduction(ScWorkOrderDetailQuery query) {
        if (StringUtils.isEmpty(query.getProcessNameEq())) {
            SysUser sysUser = userService.selectUserById(SecurityUtils.getUserId());
            if (StringUtils.isNull(sysUser) || StringUtils.isEmpty(sysUser.getWorkshopSection())) {
                throw new ServiceException("请加入正确工段！");
            }
            query.setProcessNameEq(sysUser.getWorkshopSection());
        }
        return AjaxResult.data(scWorkOrderService.listDetailForProduction(query));
    }

    /**
     * 导出生产计划单列表
     */
//    @PreAuthorize("@ss.hasPermi('business:workOrder:export')")
    @Log(title = "生产计划单" , businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public void export(ScWorkOrderQuery query, HttpServletResponse response) {
        new ExcelUtil<>(ScWorkOrder. class).exportExcel(response,scWorkOrderService.list( WhereEntityTool.invoke(query)), "生产计划单数据");
    }

    /**
     * 获取生产计划单详细信息
     */
//    @PreAuthorize("@ss.hasAnyPermi('business:workOrder:list,business:workOrder:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(scWorkOrderService.getById(id));
    }

    /**
     * 新增生产计划单
     */
//    @PreAuthorize("@ss.hasPermi('business:workOrder:add')")
    @Log(title = "生产计划单" , businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ScWorkOrder scWorkOrder) {
        return toAjax(scWorkOrderService.save(scWorkOrder));
    }

    /**
     * 修改生产计划单
     */
//    @PreAuthorize("@ss.hasPermi('business:workOrder:edit')")
    @Log(title = "生产计划单" , businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ScWorkOrder scWorkOrder) {
        approval(scWorkOrderService.getById(scWorkOrder.getId()));
        return toAjax(scWorkOrderService.updateById(scWorkOrder));
    }

    /**
     * 删除生产计划单
     */
//    @PreAuthorize("@ss.hasPermi('business:workOrder:remove')")
    @Log(title = "生产计划单" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        ids.forEach(id -> approval(scWorkOrderService.getById(id)));
        return toAjax(scWorkOrderService.removeByIds(ids));
    }

    /**
     * 模版导出
     * @param response
     * @return
     */
    @Log(title = "生产计划单", businessType = BusinessType.EXPORT)
    @GetMapping("/exportTemplate")
    @SneakyThrows
    public AjaxResult exportTemplate(HttpServletResponse response) {
        return new ExcelUtil<>(WorkOrderExcelVo.class).importTemplateExcel("生产计划单");
    }

    /**
     * 生产计划单导入
     * @param file
     * @return
     * @throws Exception
     */
    @Log(title = "生产计划单", businessType = BusinessType.IMPORT)
    @PostMapping("/importWorkOrder")
    public AjaxResult importWorkOrder(MultipartFile file) throws Exception {
        Asserts.check(file != null && !file.isEmpty(), "文件为空，无法导入");
        List<WorkOrderExcelVo> list = new ExcelUtil<>(WorkOrderExcelVo.class).importExcel(file.getInputStream());
        return AjaxResult.success(scWorkOrderService.importWorkOrder(list));
    }

    /**
     * 开工
     * @param id
     * @return
     */
    @GetMapping("/startWork/{id}")
    public AjaxResult startWork(@PathVariable Long id) {

        return toAjax(scWorkOrderService.startWork(id));
    }

    /**
     * 结单
     * @param id
     * @return
     */
    @GetMapping("/workOver/{id}")
    public AjaxResult workOver(@PathVariable Long id) {
        return toAjax(scWorkOrderService.workOver(id));
    }

    /**
     * 拆分订单
     * @param ids
     * @return
     */
    @GetMapping("/split/{id}")
    public AjaxResult split(@PathVariable("id") Set<Long> ids) {
        return toAjax(scWorkOrderService.split(ids));
    }

    /**
     * 获取报工详情数据
     * @param detailId
     * @return
     */
    @GetMapping("/getReportingData/{detailId}")
    public AjaxResult getReportingData(@PathVariable Long detailId) {
        return AjaxResult.data(scWorkOrderService.getReportingData(detailId));
    }

    /**
     * 获取合格率报表头部
     * @param scWorkOrderQuery
     * @return
     */
    @GetMapping("/getPassRateReportHead")
    public AjaxResult getPassRateReportHead(ScWorkOrderQuery scWorkOrderQuery) {
        ScWorkOrderVo scWorkOrderVo = scWorkOrderService.getPassRateReportHead(scWorkOrderQuery);
        return AjaxResult.data(scWorkOrderVo);
    }

    /**
     * 获取合格率报表表体
     *
     * @param scWorkOrderQuery
     * @return
     */
    @GetMapping("/getPassRateReportBody")
    public TableDataInfo getPassRateReportBody(ScWorkOrderQuery scWorkOrderQuery, Page<ScWorkOrder> page) {
        Page<ScWorkOrderVo> pageVo = scWorkOrderService.getPassRateReportBody(page, scWorkOrderQuery);
        return getDataTable(pageVo);
    }
}
